package com.yinxin.tulingbio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author yinxin
 * @Title:
 * @Package
 * @Description:
 * @date 2022/1/1211:22
 */
public class BioServerSingle {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        InputStream in = null;
        OutputStream out = null;
        Socket socket = null;
        try {
            serverSocket = new ServerSocket(8080);
            //
            while (true) {
                socket = serverSocket.accept();//阻塞，进行三次握手

                //连接成功得到socket，从getInputStream拿到发过来的请求，从getOutputStream写出返回的数据。
                in = socket.getInputStream();
                out = socket.getOutputStream();
                byte[] request = new byte[1024];
                while (in.read(request) > 0) {
                    System.out.println(new String(request));
                    out.write("ok".getBytes());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
